package com.ficus.road.maintain.controller;

import com.ficus.road.maintain.authority.vo.AllFactorEmergency;
import com.ficus.road.maintain.core.model.Hit;
import com.ficus.road.maintain.core.model.HitQueryRequestDTO;
import com.ficus.road.maintain.core.model.PanelConfig;
import com.ficus.road.maintain.service.HitService;
import com.ficus.road.maintain.service.PanelService;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xiawen yang
 * @date 2021/9/9 下午2:26
 */
@RestController
public class PanelController {

    @Autowired
    private HitService hitService;

    @Autowired
    private PanelService panelService;

    /**
     * 全要素治理总数统计
     *
     * @return
     */
    @GetMapping("/allFactor/emergency")
    public ResponseEntity<AllFactorEmergency> getEmergencyIndicator() {
        AllFactorEmergency allFactorEmergency = panelService.queryEmergencyIndicator();
        return new ResponseEntity<>(allFactorEmergency, HttpStatus.OK);
    }


    @GetMapping("/panel/config")
    public ResponseEntity<PanelConfig> getPanelConfig(@RequestParam(required = false) String source) {
        PanelConfig panelConfig = panelService.getPanelConfig();
        return new ResponseEntity<>(panelConfig, HttpStatus.OK);
    }

    //按指定条件全要素查询病害
    @RequestMapping(value = "/panel/hits/query",
            produces = {"application/json"},
            consumes = {"application/json"},
            method = RequestMethod.POST)
    public ResponseEntity<List<Hit>> queryHit(@Min(0) @Valid @RequestParam(defaultValue = "0") Integer start,
                                              @Min(1) @Valid @RequestParam(defaultValue = "100000") Integer limit,
                                              @RequestParam(required = false) String cursor,
                                              @Valid @RequestBody HitQueryRequestDTO hitQueryRequest)
            throws IllegalAccessException {
        Query query = HitController.toHitQuery(hitQueryRequest.getFilter());
        query.skip(start).limit(limit);
        query.with(new Sort(Sort.Direction.DESC, "first_hit_time"));
        List<Hit> hits = panelService.queryHits(query);
        //历史病害记录清空，前端不需要这个字段
        hits.forEach(hit -> hit.setList(null));
        //根据id查符合条件的总数
        query.fields().include("_id");
        //最多返回一万条数据,防止无限分页
        query.skip(0).limit(10000);
        int total = panelService.countHitAllFactory(query);
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        Boolean isFinal = Boolean.FALSE;
        if (hits.size() != limit) {
            isFinal = Boolean.TRUE;
        }
        headers.add("X-OneAPI-Exhausted", String.valueOf(isFinal));
        headers.add("X-OneAPI-EstimatedSize", String.valueOf(total));
        return new ResponseEntity<>(hits, headers, HttpStatus.OK);
    }

    //批量查询历史病害记录
    @RequestMapping(value = "/panel/hits/getHistoryByIds",
            method = RequestMethod.POST)
    public ResponseEntity<List<Hit>> queryHistByIds(@Valid @RequestBody List<String> hitIds) {
        Criteria criteria = Criteria.where("id").in(hitIds);
        List<Hit> hits = panelService.queryHits(new Query(criteria));
        if (CollectionUtils.isEmpty(hits)) {
            return new ResponseEntity<>(Lists.newArrayList(), HttpStatus.OK);
        }
        Map<String, Hit> hitMap = hits.stream().collect(Collectors.toMap(Hit::getId, a -> a));
        List<Hit> resultList = hitIds.stream().map(item -> hitMap.get(item)).collect(Collectors.toList());
        return new ResponseEntity<>(resultList, HttpStatus.OK);
    }
}
